package com.nextbusmn.server.services;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import javax.servlet.http.HttpServletResponse;

import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.nextbusmn.server.JDOWrappers.StopTimeJDOWrapper;
import com.nextbusmn.server.JSONBuilders.StopJSONBuilder;
import com.nextbusmn.server.dataobjects.StopTimeData;

public class StopService implements AndroidService {
	
	private final String[][] requestParams;
	private HttpServletResponse response;
	
	public StopService(String[][] request, HttpServletResponse response) {
		requestParams = request;
		this.response = response;
	}
	
	@Override
	public void processRequest() {
		try {
			
			JSONArray jsonResponse = getNextSixBuses();
			
			response.setContentType("application/json");
	        response.setHeader("Cache-Control", "no-cache");
	        response.getWriter().write(jsonResponse.toString());
	        
		} catch (IOException e) {
			AndroidService errorService = 
					new ErrorService("IOError on Stop Service response", response);
			errorService.processRequest();
		} 

	}
	
	private JSONArray getNextSixBuses() {
		
		Calendar startTime;
		List<StopTimeData> nextBuses = null;
		
		if (requestParams.length > 1) {
			if (requestParams[1][0].equals("t")) {
				startTime = getDateAndTimeFromString(requestParams[1][1]);
				nextBuses = 
						StopTimeJDOWrapper.getNextTrips(Integer.parseInt(requestParams[0][1]), 6, startTime);
			} else
			if (requestParams[1][0].equals("a")) {
				nextBuses = StopTimeJDOWrapper.getAllTripsByService(Integer.parseInt(requestParams[0][1]), 
						requestParams[1][1]);
			}
		} else {
			startTime = Calendar.getInstance(TimeZone.getTimeZone("America/Chicago"));
			nextBuses = 
					StopTimeJDOWrapper.getNextTrips(Integer.parseInt(requestParams[0][1]), 6, startTime);
		}
		
//		System.out.println(new SimpleDateFormat("MM/dd/yyyy kk:mm").format(startTime.getTime()));
		
		System.out.println(nextBuses.size());
		
		return StopJSONBuilder.getNextTripJSON(nextBuses);
	}
	
	private Calendar getDateAndTimeFromString(String dtString) {
		Calendar dateTime = Calendar.getInstance();
		
		try {
			dateTime.set(Integer.parseInt(dtString.substring(0, 4)), 
					Integer.parseInt(dtString.substring(4, 6)) - 1, 
					Integer.parseInt(dtString.substring(6, 8)),		 
					Integer.parseInt(dtString.substring(8, 10)),
					Integer.parseInt(dtString.substring(10, 12)));
		} catch (NumberFormatException e) {
			AndroidService errorService = 
					new ErrorService("Cannot parse date time string", response);
			errorService.processRequest();
		}
		
		return dateTime;
	}

	
}
